iT邦幫忙

2024 iThome 鐵人賽

DAY 6
0
Kubernetes

K8s 資料庫管理系統系列 第 6

day 6 k8s 大型公司備份商業機密資料庫管理系統

  • 分享至 

  • xImage
  •  

今天是第六天我們可以寫一個k8s大型公司備份商業機密資料庫管理系統,以下是程式碼

1. 建立 Kubernetes 集群

首先,搭建一個 Kubernetes 集群,可以使用雲平台(如 GKE、EKS 或 AKS)或本地環境(如 Minikube)進行測試。

2. 資料庫容器化

將資料庫服務打包成容器,並部署在 Kubernetes 中。以下是 PostgreSQL 的範例:

創建一個 PostgreSQL 部署 (postgres-deployment.yaml):

apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres
spec:
  replicas: 1
  selector:
    matchLabels:
      app: postgres
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
      - name: postgres
        image: postgres:13
        env:
        - name: POSTGRES_USER
          value: "admin"
        - name: POSTGRES_PASSWORD
          value: "secretpassword"
        - name: POSTGRES_DB
          value: "company_secrets"
        ports:
        - containerPort: 5432
        volumeMounts:
        - name: postgres-data
          mountPath: /var/lib/postgresql/data
      volumes:
      - name: postgres-data
        persistentVolumeClaim:
          claimName: postgres-pvc
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: postgres-pvc
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi

3. 自動備份

使用 Kubernetes 的 CronJob 來定期備份資料庫。每隔一段時間將數據庫導出,並存放在遠程存儲上。

創建一個 備份 CronJob

apiVersion: batch/v1
kind: CronJob
metadata:
  name: postgres-backup
spec:
  schedule: "0 2 * * *"  # 每天凌晨 2 點執行
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: backup
            image: postgres:13
            env:
            - name: POSTGRES_USER
              value: "admin"
            - name: POSTGRES_PASSWORD
              value: "secretpassword"
            - name: POSTGRES_DB
              value: "company_secrets"
            command: ["/bin/sh", "-c"]
            args: ["pg_dump -U admin -d company_secrets > /backup/db_backup.sql && gsutil cp /backup/db_backup.sql gs://your-backup-bucket/$(date +%Y-%m-%d)_db_backup.sql"]
            volumeMounts:
            - name: backup-storage
              mountPath: /backup
          restartPolicy: OnFailure
          volumes:
          - name: backup-storage
            emptyDir: {}

這個 CronJob 會每天執行資料庫的備份並將備份文件上傳至 Google Cloud Storage。

4. 加密處理

在備份過程中對數據進行加密,可以使用 gpg 等工具在備份前進行加密處理。

修改備份腳本來加密數據:

args: ["pg_dump -U admin -d company_secrets | gpg --symmetric --cipher-algo AES256 -o /backup/db_backup.sql.gpg && gsutil cp /backup/db_backup.sql.gpg gs://your-backup-bucket/$(date +%Y-%m-%d)_db_backup.sql.gpg"]

5. 監控與告警

安裝 Prometheus 和 Grafana,並通過 K8s 的 metrics-server 來收集系統狀態和資源使用情況。

Prometheus 部署示例:

kubectl apply -f https://raw.githubusercontent.com/prometheus-operator/kube-prometheus/main/manifests/setup/
kubectl apply -f https://raw.githubusercontent.com/prometheus-operator/kube-prometheus/main/manifests/

可以設定告警規則來監控備份任務的成功與失敗。

6. 權限管理

透過 Kubernetes RBAC 控制誰可以操作備份相關的資源。

定義 RBAC 規則:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: default
  name: backup-role
rules:
- apiGroups: [""]
  resources: ["pods", "jobs"]
  verbs: ["get", "list", "create", "delete"]

---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: backup-rolebinding
  namespace: default
subjects:
- kind: User
  name: "backup-admin"
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: backup-role
  apiGroup: rbac.authorization.k8s.io

這樣可以確保只有指定用戶可以執行和管理備份任務。

1. PostgreSQL 資料庫的 Deployment 和 PVC

首先,我們部署了 PostgreSQL 資料庫,並為其持久化存儲配置 PVC (Persistent Volume Claim) 來確保數據不會因為 Pod 重啟或調度到其他節點而丟失。

postgres-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres
spec:
  replicas: 1
  selector:
    matchLabels:
      app: postgres
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
      - name: postgres
        image: postgres:13
        env:
        - name: POSTGRES_USER
          value: "admin"
        - name: POSTGRES_PASSWORD
          value: "secretpassword"
        - name: POSTGRES_DB
          value: "company_secrets"
        ports:
        - containerPort: 5432
        volumeMounts:
        - name: postgres-data
          mountPath: /var/lib/postgresql/data
      volumes:
      - name: postgres-data
        persistentVolumeClaim:
          claimName: postgres-pvc
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: postgres-pvc
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
  • apiVersion: apps/v1kind: Deployment:指定我們在創建一個 Kubernetes Deployment,用來管理資料庫容器的副本。
  • metadataspec:設定了 Deployment 的名字 (postgres),並告訴 Kubernetes 應該如何部署這個資料庫。
    • replicas: 1:只運行一個副本。
    • containers 部分:指定了容器的設定:
      • 使用 postgres:13 映像作為容器的基礎。
      • 定義了三個環境變量:POSTGRES_USERPOSTGRES_PASSWORDPOSTGRES_DB,用來初始化資料庫的用戶名、密碼和資料庫名稱。
      • volumeMounts:將名為 postgres-data 的 volume 掛載到 /var/lib/postgresql/data,用來存儲資料庫數據。
    • volumes 部分:將這個 volume 和 PVC (PersistentVolumeClaim) 綁定,確保數據持久化存儲在物理卷中。

PVC 是一個請求存儲的方式,這裡請求了 10GiB 的存儲空間 (storage: 10Gi)。

2. 備份 CronJob

我們使用 Kubernetes 的 CronJob 來定時執行備份工作。這個部分定義了每天執行一次資料庫的自動備份,並將備份數據上傳到雲端存儲(如 Google Cloud Storage)。

備份 CronJob

apiVersion: batch/v1
kind: CronJob
metadata:
  name: postgres-backup
spec:
  schedule: "0 2 * * *"  # 每天凌晨 2 點執行
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: backup
            image: postgres:13
            env:
            - name: POSTGRES_USER
              value: "admin"
            - name: POSTGRES_PASSWORD
              value: "secretpassword"
            - name: POSTGRES_DB
              value: "company_secrets"
            command: ["/bin/sh", "-c"]
            args: ["pg_dump -U admin -d company_secrets > /backup/db_backup.sql && gsutil cp /backup/db_backup.sql gs://your-backup-bucket/$(date +%Y-%m-%d)_db_backup.sql"]
            volumeMounts:
            - name: backup-storage
              mountPath: /backup
          restartPolicy: OnFailure
          volumes:
          - name: backup-storage
            emptyDir: {}
  • apiVersion: batch/v1kind: CronJob:定義了一個 CronJob,它會在指定的時間調度備份任務。
  • schedule: "0 2 * * *":定義了備份的執行時間,這裡是每天凌晨 2 點。
  • jobTemplate:定義了每次備份任務所使用的容器和指令:
    • containers 部分:使用和資料庫相同的 postgres:13 映像,但這裡的目的是執行資料庫備份操作。
      • commandargs:我們使用 pg_dump 指令來導出資料庫數據到 /backup/db_backup.sql,然後使用 gsutil 指令將備份文件上傳至 Google Cloud Storage。
    • volumeMounts:將一個空的臨時卷 (emptyDir) 掛載到 /backup,用來存儲暫時的備份文件。

備份任務設置為 restartPolicy: OnFailure,這意味著如果備份任務失敗,會自動重新嘗試。

3. 加密備份數據

我們在傳輸數據之前,使用加密工具(如 gpg)來加密資料庫備份文件,確保數據安全。以下是加密命令的解釋:

args: ["pg_dump -U admin -d company_secrets | gpg --symmetric --cipher-algo AES256 -o /backup/db_backup.sql.gpg && gsutil cp /backup/db_backup.sql.gpg gs://your-backup-bucket/$(date +%Y-%m-%d)_db_backup.sql.gpg"]
  • pg_dump -U admin -d company_secrets:這條命令導出資料庫數據。
  • gpg --symmetric --cipher-algo AES256 -o /backup/db_backup.sql.gpg:這條命令使用對稱加密技術和 AES-256 算法來加密備份數據,並將結果保存為 .gpg 文件。
  • gsutil cp:上傳加密文件到雲端存儲。

4. 監控與告警

你可以使用 Kubernetes 內建的 metrics-server 搭配 Prometheus 和 Grafana 來實現監控和告警功能。監控系統會定期檢查任務執行的狀況,並在備份失敗或其他異常情況下發送告警通知。

Prometheus 部署:

kubectl apply -f https://raw.githubusercontent.com/prometheus-operator/kube-prometheus/main/manifests/setup/
kubectl apply -f https://raw.githubusercontent.com/prometheus-operator/kube-prometheus/main/manifests/

這會安裝 Prometheus,用來監控整個 Kubernetes 集群的狀態。

5. 權限管理 (RBAC)

最後,通過 Kubernetes 的角色基於權限 (RBAC) 控制,確保只有授權用戶可以操作備份系統。

RBAC 規則:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: default
  name: backup-role
rules:
- apiGroups: [""]
  resources: ["pods", "jobs"]
  verbs: ["get", "list", "create", "delete"]

---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: backup-rolebinding
  namespace: default
subjects:
- kind: User
  name: "backup-admin"
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: backup-role
  apiGroup: rbac.authorization.k8s.io
  • Role:定義了可以操作備份相關資源的權限(如 Pods 和 Jobs)。
  • RoleBinding:將這些權限綁定到特定的用戶 (backup-admin),使其可以管理備份相關操作。

總結

這個 Kubernetes 系統的每個組件協同運作,確保資料庫的備份能夠自動化、安全地執行。通過容器化、定時任務、加密和權限控制,我們構建了一個穩定可靠的備份方案。同時監控和告警功能也為系統的穩定運行提供了保障。


上一篇
day 5 k8s 資料庫管理大賣場系統
下一篇
day 7 k8s的歷史
系列文
K8s 資料庫管理系統15
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言